const Nightmare=require("nightmare")
const request=require("request")
const path = require('path');
var fs = require('fs-extra');
var Fiber = require('fibers');
const rootNight=Nightmare({
   show:true
});

String.prototype.startWith=function(str){
   var reg=new RegExp("^"+str);
   return reg.test(this);
}

String.prototype.endWith=function(str){
var reg=new RegExp(str+"$");
return reg.test(this);
}

Array.prototype.unique = function()
{
	var n = {},r=[]; //n为hash表，r为临时数组
	for(var i = 0; i < this.length; i++) //遍历当前数组
	{
		if (!n[this[i]]) //如果hash表中没有当前项
		{
			n[this[i]] = true; //存入hash表
			r.push(this[i]); //把当前数组的当前项push到临时数组里面
		}
	}
	return r;
}

rootNight.goto("http://www.win4000.com/meinvtag10290.html").wait(".main_cont").evaluate(function(){
         var links=[];
         $("a").each(function(ind,inv){
               var href=$(inv).attr("href");
               links.push(href);
         });
         return links;
}).end().then(links=>{
   let vLinks=[];
   
   links.forEach(function(link){
      if(link.startWith("/")){
         vLinks.push("http://www.win4000.com"+link);
      }
      else if(link.startWith("http://www.win4000.com")&&link.endWith(".html")){
         vLinks.push(link);
      }
   })
   
  
   let temNight=Nightmare({show:true});
   Fiber(function(){
      let downloadImgs=[];
      vLinks=vLinks.unique();
      vLinks.some(function(link){
         console.info("Start Link!");
            let htmlFiber=Fiber.current;
            temNight.goto(link).wait(".main_cont").evaluate(function(){
               var imgSrcs=[];
               $("img").each(function(ind,inv){
                  var src=$(inv).attr("src");
                  imgSrcs.push(src); 
               })
               return imgSrcs;
            }).then(function(imgSrcs){
                 imgSrcs.forEach(src=>{
                  downloadImgs.push(src);
                 })
                 htmlFiber.run();
            }).catch(error=>{
               console.error(error);
            })
            Fiber.yield();
            console.info("Link:"+link+" Over!")
      });
      
      temNight.end().catch(error=>{
         console.error(temNight);
      })

      downloadImgs=downloadImgs.unique();
      downloadImgs.forEach(function(url){
         try{
            var diskPath=__dirname+"/download/"+path.basename(url);
            request(url).pipe(fs.createWriteStream(diskPath)).on('close',function(){
               console.log(url+" download!")
            })
         }
         catch(error){
            console.error(error);
         }
      });


   }).run();
}).catch(error=>{
   console.error(error);
});